import { useState, useEffect, useCallback, useRef } from 'react'

// 组件懒加载管理器
class LazyLoadManager {
  constructor() {
    this.cache = new Map()
    this.loading = new Map()
  }

  // 懒加载组件
  async loadComponent(loader, key) {
    // 检查缓存
    if (this.cache.has(key)) {
      return this.cache.get(key)
    }

    // 检查是否正在加载
    if (this.loading.has(key)) {
      return this.loading.get(key)
    }

    // 开始加载
    const loadPromise = loader().then(module => {
      const component = module.default || module
      this.cache.set(key, component)
      this.loading.delete(key)
      return component
    }).catch(error => {
      this.loading.delete(key)
      console.warn(`Failed to load component: ${key}`, error)
      throw error
    })

    this.loading.set(key, loadPromise)
    return loadPromise
  }

  // 预加载组件
  preloadComponent(loader, key) {
    if (!this.cache.has(key) && !this.loading.has(key)) {
      this.loadComponent(loader, key).catch(() => {
        // 预加载失败不影响主流程
      })
    }
  }

  // 清除缓存
  clearCache(key) {
    if (key) {
      this.cache.delete(key)
    } else {
      this.cache.clear()
    }
  }
}

// 全局懒加载管理器
const lazyLoadManager = new LazyLoadManager()

// 代码分割Hook
export const useCodeSplitting = () => {
  const [loadedComponents, setLoadedComponents] = useState(new Map())
  const loadingRef = useRef(new Set())

  // 懒加载组件
  const lazyLoad = useCallback(async (loader, key) => {
    // 检查是否已加载
    if (loadedComponents.has(key)) {
      return loadedComponents.get(key)
    }

    // 检查是否正在加载
    if (loadingRef.current.has(key)) {
      // 等待加载完成
      return new Promise((resolve) => {
        const checkLoaded = () => {
          if (loadedComponents.has(key)) {
            resolve(loadedComponents.get(key))
          } else {
            setTimeout(checkLoaded, 50)
          }
        }
        checkLoaded()
      })
    }

    try {
      loadingRef.current.add(key)
      const component = await lazyLoadManager.loadComponent(loader, key)
      
      setLoadedComponents(prev => new Map(prev).set(key, component))
      return component
    } finally {
      loadingRef.current.delete(key)
    }
  }, [loadedComponents])

  // 预加载组件
  const preload = useCallback((loader, key) => {
    lazyLoadManager.preloadComponent(loader, key)
  }, [])

  // 批量预加载
  const preloadBatch = useCallback((components) => {
    components.forEach(({ loader, key }) => {
      preload(loader, key)
    })
  }, [preload])

  // 清除缓存
  const clearCache = useCallback((key) => {
    lazyLoadManager.clearCache(key)
    setLoadedComponents(prev => {
      const newMap = new Map(prev)
      if (key) {
        newMap.delete(key)
      } else {
        newMap.clear()
      }
      return newMap
    })
  }, [])

  return {
    lazyLoad,
    preload,
    preloadBatch,
    clearCache,
    loadedComponents
  }
}

// 路由级别的代码分割 - 简化版本
export const useRouteCodeSplitting = () => {
  const { preload } = useCodeSplitting()

  // 预加载相关路由 - 简化实现
  const preloadRelatedRoutes = useCallback((currentRoute) => {
    // 这里可以根据需要添加实际的路由预加载逻辑
    if (process.env.NODE_ENV === 'development') {
      console.log(`预加载相关路由: ${currentRoute}`)
    }
    
    // 示例：预加载相关路由
    const relatedRoutes = {
      'product-detail': ['category', 'hospital-detail'],
      'hospital-detail': ['product-detail', 'category'],
      'category': ['product-detail', 'hospital-detail']
    }

    const routes = relatedRoutes[currentRoute] || []
    if (process.env.NODE_ENV === 'development') {
      console.log(`相关路由: ${routes.join(', ')}`)
    }
  }, [preload])

  return {
    preloadRelatedRoutes
  }
}

// 组件级别的代码分割 - 简化版本
export const useComponentCodeSplitting = () => {
  const { preload } = useCodeSplitting()

  // 预加载组件 - 简化实现
  const preloadComponent = useCallback((componentName) => {
    if (process.env.NODE_ENV === 'development') {
      console.log(`预加载组件: ${componentName}`)
    }
  }, [preload])

  return {
    preloadComponent
  }
}

export default useCodeSplitting
